package com.hshit.downloader.adapter;

import java.util.List;
import java.util.Map;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageButton;
import android.widget.TextView;

import com.hshit.downloader.R;

public class DownLoadAdapter extends BaseAdapter {

	private LayoutInflater mInflater;
	private List<Map<String, String>> data;
	private Context context;
	private CallBackPressDownload mCallBack;

	public DownLoadAdapter(Context context, List<Map<String, String>> data, CallBackPressDownload mCallBack) {
		this.context = context;
		mInflater = LayoutInflater.from(context);
		this.data = data;
		this.mCallBack = mCallBack;
	}

	public void refresh(List<Map<String, String>> data) {
		this.data = data;
		this.notifyDataSetChanged();
	}

	@Override
	public int getCount() {
		return data.size();
	}

	@Override
	public Object getItem(int position) {
		return data.get(position);
	}

	@Override
	public long getItemId(int position) {
		return position;
	}

	@Override
	public View getView(final int position, View convertView, ViewGroup parent) {
		final Map<String, String> bean = data.get(position);
		ViewHolder holder = null;
		if (convertView == null) {
			convertView = mInflater.inflate(R.layout.layout_item_download, null);
			holder = new ViewHolder();
			holder.resouceName = (TextView) convertView
					.findViewById(R.id.tv_resouce_name);
			holder.startDownload = (ImageButton) convertView
					.findViewById(R.id.btn_start);
			holder.pauseDownload = (ImageButton) convertView
					.findViewById(R.id.btn_pause);
			convertView.setTag(holder);
		} else {
			holder = (ViewHolder) convertView.getTag();
		}
		holder.resouceName.setText(bean.get("name"));
		holder.startDownload.setOnClickListener(new OnClickListener() {
				@Override
				public void onClick(View v) {
					mCallBack.onClickDownload(bean.get("link"), bean.get("name"), bean.get("singer"), v);
				}
			});
		
		holder.pauseDownload.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				mCallBack.onClickPause(bean.get("link"), v);
			}
		});
		return convertView;
	}

	private class ViewHolder {
		public TextView resouceName;
		public ImageButton startDownload;
		public ImageButton pauseDownload;
	}
	
	public static interface CallBackPressDownload {
		public void onClickDownload(String url, String name, String singer, View v);
		public void onClickPause(String url, View v);
	}
}